import fs from 'fs'
import { fileURLToPath, pathToFileURL } from 'url'


//findControllers方法，找到控制器文件的路径
function findControllers() {
    //解析出controllers的文件URL
    let xDir = new URL('../controllers', import.meta.url);
    let controllerDir = fileURLToPath(xDir);//转换为本地文件系统路径

    //判断文件是否存在
    if (fs.existsSync(controllerDir)) {
        //存在，用同步方法读取所有文件
        let allFile = fs.readdirSync(controllerDir);
        //找到controllers文件后转换为文件URL
        let allControllersfile = allFile.filter(item => item.endsWith('.js')).map(item => pathToFileURL(controllerDir + '/' + item));
        // console.log(allControllersfile);
        

        return allControllersfile;

    }
    return null;

}



//registerRoute方法，遍历所有控制器，注册函数
function registerRoute(router, controllers) {
    if (controllers === null) {
        return
    }

    //遍历控制器文件
    controllers.forEach(async item => {
        //动态导入
        let {obj} = await import(item);

        //遍历模块中的对象
        for(var key in obj ){
            let [keyMethod,keyPath]=key.split(' ');
            let keyFn = obj[key];

            if(keyMethod === 'get'){
                router.get(keyPath,keyFn);
            }
            if(keyMethod === 'post'){
                router.post(keyPath,keyFn);
            }
            if(keyMethod === 'put'){
                router.put(keyPath,keyFn);
            }
            if(keyMethod === 'delete'){
                router.delete(keyPath,keyFn);
            }
        }
    });
}


export const findAllControllers = findControllers

export const regRoute = registerRoute

